package com.ttg.utils.connection.handler;

//~--- non-JDK imports --------------------------------------------------------

import com.alibaba.fastjson.JSON;
import com.ttg.utils.Assert;
import com.ttg.utils.Bytes;
import com.ttg.utils.connection.SignatureInfo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpResponseException;
import org.apache.http.entity.ContentType;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.nio.charset.Charset;

//~--- JDK imports ------------------------------------------------------------

/**
 * Class	ResponseHandlerHelper
 * Description	
 * Create	2015.09.11 at 01:31:41 CST
 * @author	Ardy    
 */
public abstract class ResponseHandlerHelper {

    /** 
     * Field log
     * Description 
     */
    private static final Log logger = LogFactory.getLog(ResponseHandlerHelper.class);

    /**
     * Constructs	ResponseHandlerHelper
     * Description
     */
    public ResponseHandlerHelper() {}

    /**
     * Method handleNon2xxStatus
     * Description
     *
     * @param	response HttpResponse
     * @return	HttpEntity
     *
     * @throws IOException
     */
    public static HttpEntity handleNon2xxStatus(HttpResponse response) throws IOException {
        StatusLine statusLine = response.getStatusLine();
        HttpEntity entity     = response.getEntity();

        if (statusLine.getStatusCode() >= 300) {
            Charset responseCharset = getResponseCharset(entity);
            String  result          = EntityUtils.toString(entity, responseCharset);

            EntityUtils.consume(entity);

            throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase() + ':' + result);
        } else {
            return entity;
        }
    }

    /**
     * Method getResponseCharset
     * Description
     *
     * @param	entity HttpEntity
     * @return	Charset
     */
    public static Charset getResponseCharset(HttpEntity entity) {
        ContentType contentType = ContentType.getOrDefault(entity);
        Charset     charset     = contentType.getCharset();

        if (charset == null) {
            charset = Charset.forName("UTF-8");
        }

        return charset;
    }

    /**
     * Method copy
     * Description
     *
     * @param	content InputStream
     * @param	targetFile File
     * @return	File
     *
     * @throws IOException
     */
    public static File copy(InputStream content, File targetFile) throws IOException {
        Assert.notNull(content, "No inputStream specified");
        Assert.notNull(targetFile, "No output File specified");

        BufferedInputStream  inStream = new BufferedInputStream(content);
        BufferedOutputStream out      = new BufferedOutputStream(new FileOutputStream(targetFile));

        try {
            byte[]  buffer    = new byte[8192];
            boolean bytesRead = true;
            int     bytesRead1;

            while ((bytesRead1 = inStream.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead1);
            }

            out.flush();

            File var6 = targetFile;

            return var6;
        } finally {
            try {
                inStream.close();
            } catch (IOException var16) {
                logger.error(var16);
            }

            try {
                out.close();
            } catch (IOException var15) {
                logger.error(var15);
            }
        }
    }

    /**
     * Method getParameters
     * Description
     *
     * @param	responseEntity HttpEntity
     * @param	responseCharset Charset
     * @return	BaseHttpResponse
     *
     * @throws IOException
     */
    public static BaseHttpResponse getParameters(HttpEntity responseEntity, Charset responseCharset)
            throws IOException {
        InputStream in     = responseEntity.getContent();
        byte[]      buffer = new byte[4];
        int         read   = in.read(buffer, 0, 4);

        if (read == 4) {
            int parametersBytesLength = Bytes.bytes2int(buffer);

            buffer = new byte[parametersBytesLength];

            int read2 = in.read(buffer, 0, parametersBytesLength);

            if (read2 == parametersBytesLength) {
                SignatureInfo signatureInfo = (SignatureInfo) JSON.parseObject(new String(buffer,
                                                  responseCharset.name()), SignatureInfo.class);
                int              bizParamsStartIndex = 4 + parametersBytesLength;
                byte[]           bizParams           = Bytes.toBytes(in,
                                                           (int) responseEntity.getContentLength()
                                                           - bizParamsStartIndex);
                BaseHttpResponse br                  = new BaseHttpResponse(responseCharset);

                br.setSignatureAlgorithm(signatureInfo.getSignatureAlgorithm());
                br.setSignatureInfo(signatureInfo.getSignatureInfo());
                br.setBizParameters(bizParams);

                return br;
            } else {
                throw new HttpResponseException(500,
                                                "Response data format is not in conformity with the specification");
            }
        } else {
            throw new HttpResponseException(500, "Response data format is not in conformity with the specification");
        }
    }


    /**
     * Method handleCustomExceptionStatus
     * Description
     *
     * @param	response HttpResponse
     * @return	byte[]
     *
     * @throws IOException
     */
    public static byte[] handleCustomExceptionStatus(HttpResponse response) throws IOException {
        StatusLine statusLine = response.getStatusLine();

        if (statusLine.getStatusCode() == 288) {
            byte[] result = EntityUtils.toByteArray(response.getEntity());

            return result;
        } else {
            return null;
        }
    }
}


//~ Formatted by Jindent --- http://www.jindent.com
